package com.lingjtx.common.thread.api;

import com.lingjtx.common.core.handle.PooledObject;
import com.lingjtx.common.thread.pooling.ObjectPoolTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.function.Function;

public class WebClientExecutor {

    private final ObjectPoolTemplate<WebClient> pool;

    public WebClientExecutor(ObjectPoolTemplate<WebClient> pool) {
        this.pool = pool;
    }

    public <T> Mono<T> execute(Function<WebClient, Mono<T>> operation) {
        return Mono.using(
                pool::autoAcquire,
                pooled -> operation.apply(pooled.get()),
                PooledObject::close
        );
    }

    public <T> Flux<T> executeMany(Function<WebClient, Flux<T>> operation) {
        return Flux.using(
                pool::autoAcquire,
                pooled -> operation.apply(pooled.get()),
                PooledObject::close
        );
    }
}
